﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using NHibernate;
using ZLCMS.Data.Model;
using ZLCMS.Data.Common;
using NHibernate.Criterion;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Util;
using System.Collections.Generic;
using DotNet.Common.NHibernateUtil.QueryFilter;
using System.IO;

namespace ZLCMS.Web.SystemManage.Basics
{
    public partial class SkuOrderList : System.Web.UI.Page
    {
        protected FrameHelper _framePage;

        public string _isconfirmed;
        public string _paystatus;
        public string _shippingstatus;
        public string _isfinished;
        public string _iscancelled;

        public string _orderno;
        public string _tradeno;
        public string _memberid;
        public string _datebegin;
        public string _dateend;
        public string _owner;
        public ShopOrderProduct _orderProductDb;
        public string fromhql = " from ShopOrderInfo o,ShopOrderProduct p where o.OrderNo=p.OrderNo";
        public string selecthql = @"select distinct o ";
        QueryFilterList filters = new QueryFilterList();
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 初始化全局变量值
            //初始化全局变量值
            _isconfirmed = Request["isconfirmed"] == null ? "" : Request["isconfirmed"];
            _paystatus = Request["paystatus"] == null ? "" : Request["paystatus"];
            _shippingstatus = Request["shippingstatus"] == null ? "" : Request["shippingstatus"];
            _isfinished = Request["isfinished"] == null ? "" : Request["isfinished"];
            _iscancelled = Request["iscancelled"] == null ? "" : Request["iscancelled"];

            _orderno = Request["orderno"] == null ? "" : Request["orderno"];
            _tradeno = Request["tradeno"] == null ? "" : Request["tradeno"];
            _memberid = Request["memberid"] == null ? "" : Request["memberid"];
            _datebegin = Request["datebegin"] == null ? "" : Request["datebegin"];
            _dateend = Request["dateend"] == null ? "" : Request["dateend"];
            _owner = UserKit.GetUserAccountFailLogin();
            #endregion

            #region 初始化控件值
            ///初始化控件值
            ParamKit.Bind("OrderIsConfirmed", ddl_isconfirmed, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, "-1", "-1");
            ddl_isconfirmed.SelectedValue = _isconfirmed;

            ParamKit.Bind("OrderPayStatus", ddl_paystatus, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, "-1", "-1");
            ddl_paystatus.SelectedValue = _paystatus;

            ParamKit.Bind("OrderShippingStatus", ddl_shippingstatus, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, "-1", "-1");
            ddl_shippingstatus.SelectedValue = _shippingstatus;

            ParamKit.Bind("OrderIsFinish", ddl_isfinished, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, "-1", "-1");
            ddl_isfinished.SelectedValue = _isfinished;

            ParamKit.Bind("OrderIsCancel", ddl_iscancelled, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, null, "-1", "-1");
            ddl_iscancelled.SelectedValue = _iscancelled;

            if (!IsPostBack)
            {
                
            }

            

            tb_search_orderno.Text = _orderno;
            tb_search_tradeno.Text = _tradeno;
            tb_search_memberid.Text = _memberid;
            tb_search_datebegin.Text = _datebegin;
            tb_search_dateend.Text = _dateend; 
            #endregion

            //初始化DWZ分页控件
            _framePage = new ZLCMS.Business.DwzFrame.FrameHelper(this);
            //设置分页大小
            int pageSize = _framePage.IsAjaxPagerPostBack ? _framePage.PageSize : 20;

            //设置页码
            int pageIndex = _framePage.IsAjaxPagerPostBack ? _framePage.PageIndex : 1;
            SetupCondition();
            if (!string.IsNullOrEmpty(Request["exportexcel"]))
            {
                using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {

                    IQuery query = session.CreateQuery("select count(*) " + fromhql);
                    filters.SetUp(query);

                    //设置记录总数
                    _framePage.RecordCount = Convert.ToInt32(query.UniqueResult());

                    query = session.CreateQuery(selecthql+fromhql + " order by o.OrderTime desc");
                    filters.SetUp(query);

                    IList<ShopOrderInfo> list = query.SetFirstResult((pageIndex - 1) * pageSize)
                                                .SetMaxResults(pageSize)
                                                .List<ShopOrderInfo>();

                    StringWriter sw = new StringWriter();

                    sw.WriteLine("订单号\t交易号\t下订时间\t用户名\t昵称\t收货人\t收货人电话\t收货人地址\t实际支付\t订单状态");
                    foreach (ShopOrderInfo item in list)
                    {
                            sw.WriteLine("" + item.OrderNo + "\t" + item.TradeNo +  "\t" + item.OrderTime.ToShortDateString() + "\t" + GetMemberRealName(item.MemberAccount).Telephone + "\t"
                                 + GetMemberRealName(item.MemberAccount).MemberName + "\t" + item.ReceiverName + "\t" + item.ReceiverPhone + "\t" +
                                item.ReceiverAddress.Trim() + "\t"  + string.Format("{0:F2}", item.TotalPrice) + "\t["
                                + ParamKit.GetValue("OrderIsConfirmed", item.IsConfirmed, " ")
                                + "][" + ParamKit.GetValue("OrderPayStatus", item.PayStatus, " ")
                                + "][" + ParamKit.GetValue("OrderIsFinish", item.IsFinished, " ")
                                + "][" + ParamKit.GetValue("OrderIsCancel", item.IsCancelled, " ")
                                + "]\t");
                      
                    }
                    sw.Close();

                    OutputKit.OutputExcel(Response, sw);

                }
            }
            else
            {
                BindList(_framePage.PageIndex, _framePage.PageSize,filters);
            }
        }

        #region 填充网格数据 + protected void BindList(int pageIndex, int pageSize)
        /// <summary>
        /// 填充网格数据
        /// </summary>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageSize">分页大小</param>
        protected void BindList(int pageIndex, int pageSize, QueryFilterList filters)
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                IQuery query = session.CreateQuery("select count(*) " + fromhql);
                filters.SetUp(query);

                //设置记录总数
                _framePage.RecordCount = Convert.ToInt32(query.UniqueResult());

                query = session.CreateQuery(selecthql + fromhql + " order by o.OrderTime desc");
                filters.SetUp(query);

                query.SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize);

                grid.DataSource = query.List<ShopOrderInfo>();
                grid.DataBind();
            }
        }
        #endregion

        #region 填充查询条件 + private void SetupCondition(ref ICriteria criteria)
        /// <summary>
        /// 填充查询条件
        /// </summary>
        /// <param name="criteria"></param>
        private void SetupCondition()
        {
            if (_isconfirmed.Trim() != "-1" && !string.IsNullOrEmpty(_isconfirmed))
            {
                filters.Add(new StringFilter("o.IsConfirmed", "IsConfirmed", _isconfirmed));//是否确认订单
            }

            if (_paystatus.Trim() != "-1" && !string.IsNullOrEmpty(_paystatus))
            {
                filters.Add(new StringFilter("o.PayStatus", "PayStatus", _paystatus));//支付状态
            }

            if (_shippingstatus.Trim() != "-1" && !string.IsNullOrEmpty(_shippingstatus))
            {
                filters.Add(new StringFilter("o.ShippingStatus", "ShippingStatus", _shippingstatus));//物流状态
            }

            if (_isfinished.Trim() != "-1" && !string.IsNullOrEmpty(_isfinished))
            {
                filters.Add(new StringFilter("o.IsFinished", "IsFinished", _isfinished));//物流状态
            }

            if (_iscancelled.Trim() != "-1" && !string.IsNullOrEmpty(_iscancelled))
            {
                filters.Add(new StringFilter("o.IsCancelled", "IsCancelled", _iscancelled));//是否取消
            }

            if (!string.IsNullOrEmpty(_orderno))
            {
                filters.Add(new StringFilter("o.OrderNo", "OrderNo", "%" + _orderno + "%", StringCompairType.Like));
            }
            if (!string.IsNullOrEmpty(_tradeno))
            {
                filters.Add(new StringFilter("o.TradeNo", "TradeNo", "%" + _tradeno + "%", StringCompairType.Like));
            }

            if (!string.IsNullOrEmpty(_memberid))
            {
                filters.Add(new StringFilter("o.MemberAccount", "MemberAccount", "%" + GetMemberAccount(_memberid) + "%", StringCompairType.Like));
            }
     
            if (!string.IsNullOrEmpty(_datebegin))
            {
                filters.Add(new NumberFilter("o.OrderTime", "start", DateTime.Parse(_datebegin), NumberCompairType.Ge));
            }
            if (!string.IsNullOrEmpty(_dateend))
            {
                filters.Add(new NumberFilter("o.OrderTime", "end", DateTime.Parse(_dateend).AddHours(23).AddMinutes(59).AddSeconds(59), NumberCompairType.Le));
            }
            if (!string.IsNullOrEmpty(_owner))
            {
                filters.Add(new StringFilter("o.OwnerAccount","OwnerAccount", _owner));
            }

            //criteria.AddOrder(Order.Desc("OrderTime"));
            foreach (DataFilter filter in filters)
            {
                fromhql += " and " + filter.GetSection();
            }
        }
        #endregion


        #region 获取会员真实姓名 + protected MemberInfo GetMemberRealName(object account)
        /// <summary>
        /// 获取会员真实姓名
        /// </summary>
        /// <returns></returns>
        protected MemberInfo GetMemberRealName(object account)
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                MemberInfo member = session.CreateCriteria<MemberInfo>().Add(Expression.Eq("OwnerAccount", _owner)).Add(Expression.Eq("AccountId", account.ToString())).UniqueResult<MemberInfo>();

                return member == null ? new MemberInfo() : member;
            }
        }
        #endregion

        #region 获取套餐名 + protected ShopOrderProduct GetTCName(object orderno)
        /// <summary>
        /// 获取会员真实姓名
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        protected ShopOrderProduct GetTCName(object orderNo)
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                ShopOrderProduct product = session.CreateCriteria<ShopOrderProduct>().Add(Expression.Eq("OwnerAccount", _owner)).Add(Expression.Eq("OrderNo", orderNo.ToString())).SetMaxResults(1).UniqueResult<ShopOrderProduct>();

                return product == null ? new ShopOrderProduct() : product;
            }
        }
        #endregion
        #region 获取会员account + protected string GetMemberAccount(object account)
        /// <summary>
        /// 获取会员真实姓名
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        protected string GetMemberAccount(object account)
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                MemberInfo member = session.CreateCriteria<MemberInfo>().Add(Expression.Eq("OwnerAccount", _owner)).Add(Expression.Eq("Telephone", account.ToString())).UniqueResult<MemberInfo>();

                return member == null ? "" : member.AccountId;
            }
        }
        #endregion
    }
}
